﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Frame.Models;
using Tools;
using System.Web.SessionState;

namespace Frame.Controllers
{
    public class FrameController : Controller
    {
        [HttpGet]
        public ActionResult Main()
        {
            return View(new MainModel(SessionKey.CheckKeyThrow()).GetMain());
        }

        public ActionResult Login()
        {
            if (Request.Form["username"] != null && Request.Form["password"] != null)
            {
                if (HttpContext.Application["ValidateCode_" + Request.UserHostAddress] != null)
                    if (ValidateCode.CheckCode(Request.Form["validate"]))
                    {
                        HttpContext.Application.Remove("ValidateCode_" + Request.UserHostAddress);
                        ViewBag.validate = null;
                    }
                    else
                    {
                        ViewBag.validate = true;
                        return View();
                    }

                LoginModel loginModel = new LoginModel(Request.Form["username"]);
                SymmetricMethod symmetricMethod = new SymmetricMethod();

                if (loginModel.GetPassword() != null)
                    if (symmetricMethod.Encrypto(Request.Form["password"]) == loginModel.GetPassword().ToString())
                    {
                        SessionKey.SetSessionKey(Request.Form["username"].ToString(), loginModel.GetUsername().ToString());
                    }
                    else
                        HttpContext.Application.Add("ValidateCode_" + Request.UserHostAddress, DateTime.Now);
            }
            else
            {
                Session.RemoveAll();
                Tools.SessionDictionary.RemoveSession(Session.SessionID, "AsynchronousUserID");
                Tools.SessionDictionary.RemoveSession(Session.SessionID, "AsynchronousLoginTime");
                Tools.SessionDictionary.RemoveSession(Session.SessionID, "Username");
                Tools.SessionDictionary.RemoveSession(Session.SessionID, "Lock");
            }
            return View();
        }

        public ActionResult Validate()
        {
            return View();
        }

        public ActionResult Coming()
        {
            return View();
        }

        [HttpPost]
        public ActionResult KeepLogin()
        {
            if (Session["KeepLogin"] == null)
                Session.Add("KeepLogin", 1);
            else
                Session["KeepLogin"] = (int)Session["KeepLogin"] + 1;
            return Json(new { Success = true, Message = "操作成功。", ReturnData = (int)Session["KeepLogin"] });
        }
    }
}
